package com.golddaymicromall.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.adapter.GoodsValueAdvrstAdapter;
import com.golddaymicromall.adapter.GoodsValueLvAdapter;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.ProductAllInfo;
import com.golddaymicromall.bean.ProductDetailInfo;
import com.golddaymicromall.bean.ProductInfo;
import com.golddaymicromall.model.WindowModel;
import com.golddaymicromall.util.ButtonUtils;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.golddaymicromall.view.GoodsScrollView;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;


public class PruductDetialActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, TextWatcher, AbsListView.OnScrollListener {
    private List<ProductInfo> listFlag = new ArrayList<ProductInfo>();
    private List<ProductAllInfo> list1;//首页列表数据
    private List<ProductInfo> list2;
    private List<ProductInfo> list3;
    private String id;
    private GoodsScrollView mSc;
    //自定scrollview中上方显示
    private View UpView;
    private ViewPager mVp;
    private LinearLayout mPointLinear;
    private TextView mTitleTv;
    private TextView mGoodsValue_DisCountTv;
    private TextView mGoodsValue_PriceTv;
    private GoodsValueAdvrstAdapter adverstAdater;
    //顶部大图点图标
    private Bitmap pBit;
    private Bitmap nBit;
    //自定scrollview中下方显示view
    private ListView DownView;
    private GoodsValueLvAdapter adapter;
    private LinearLayout mBackImg;
    private String uoukeId;
    ProgressBar progress;
    ListView goodlv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pruduct_detial);
        uoukeId = SPUtils.get(getApplicationContext(), "Id", "").toString();
        id = getIntent().getStringExtra("id");
        initView();
        WindowModel.WIDTH = getWindowManager().getDefaultDisplay().getWidth();
        initList();
    }

    //ca7745810
    protected void initList() {
        attemptproduct();
        pBit = BitmapFactory.decodeResource(getResources(), R.drawable.home_banner_dot_down);
        nBit = BitmapFactory.decodeResource(getResources(), R.drawable.home_banner_dot_down_black);
    }

    private void attemptproduct() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.product.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("id", id);
        form.put("logid", uoukeId);
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();

                    list1 = new ArrayList<ProductAllInfo>();
                    list2 = new ArrayList<ProductInfo>();
                    list3 = new ArrayList<ProductInfo>();
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            list1 = JSON.parseArray(result, ProductAllInfo.class);
                            mTitleTv.setText(list1.get(0).getResult().get(0).getProductname());
                            mGoodsValue_DisCountTv.setText(list1.get(0).getResult().get(0).getSkucode());
                            mGoodsValue_PriceTv.setText("￥ " + list1.get(0).getResult().get(0).getPrice());
                            listFlag.add(list1.get(0).getResult().get(0));
                            for (int i = 0; i < list1.get(0).getResult().size(); i++) {
                                if ("1".equals(list1.get(0).getResult().get(i).getImagetype())) {
                                    list2.add(list1.get(0).getResult().get(i));
                                }
                            }
                            adapter = new GoodsValueLvAdapter(goodlv, list2, PruductDetialActivity.this);
                            //新添
                            goodlv.setAdapter(adapter);
                            for (int i = 0; i < list1.get(0).getResult().size(); i++) {
                                if ("0".equals(list1.get(0).getResult().get(i).getImagetype())) {
                                    list3.add(list1.get(0).getResult().get(i));
                                }
                            }
                            adverstAdater = new GoodsValueAdvrstAdapter(list3, PruductDetialActivity.this);
                            mVp.setAdapter(adverstAdater);
                            //动态创建viewpager下索引点
                            createPoint();
                            mSc.measureLv(goodlv);
                            mSc.smoothScrollTo(0, 0);
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }

                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    public void onResume() {
        super.onResume();
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        switch (scrollState) {
            case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 滑动状态
                ProductDetailInfo.threadFlag = false;
                break;
            case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 停止
                ProductDetailInfo.threadFlag = true;
                break;
            case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 触摸listView
                ProductDetailInfo.threadFlag = false;
                break;
            default:

                break;
        }
    }


    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {
    }

    protected void initView() {
        progress = (ProgressBar) findViewById(R.id.progress);

        mBackImg = (LinearLayout) findViewById(R.id.GoodsValue_BackImg);
        mBackImg.setOnClickListener(this);
        mSc = (GoodsScrollView) findViewById(R.id.GoodsValue_Sc);
        //加载上部界面
        UpView = View.inflate(this, R.layout.view_goodsvalue_up, null);
        mVp = (ViewPager) UpView.findViewById(R.id.GoodsValue_Vp1);
        goodlv = (ListView) UpView.findViewById(R.id.goodlv);
        mPointLinear = (LinearLayout) UpView.findViewById(R.id.GoodsValue_VpLinear);
        mTitleTv = (TextView) UpView.findViewById(R.id.GoodsValue_TitleTvdetile);
        mGoodsValue_DisCountTv = (TextView) UpView.findViewById(R.id.GoodsValue_DisCountTvdetil);
        mGoodsValue_PriceTv = (TextView) UpView.findViewById(R.id.GoodsValue_PriceTvdetil);
        mVp.setOnPageChangeListener(this);
        mSc.setUpView(UpView);
        mVp.setOnPageChangeListener(this);
        goodlv.setOnScrollListener(this);

        //加载下部界面
        DownView = (ListView) View.inflate(this, R.layout.view_goodsvalue_down, null);
        mBackImg.setOnClickListener(this);
        mSc.setDownView(DownView);

    }


    //动态创建viewpager下索引点
    private void createPoint() {
        int i;
        for (i = 0; i < list3.size(); i++) {
            ImageView img = new ImageView(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams
                    (LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.rightMargin = 5;
            img.setLayoutParams
                    (lp);
            if (i == 0)
                img.setImageBitmap(pBit);
            else
                img.setImageBitmap(nBit);
            mPointLinear.addView(img, i);
        }
    }

    @Override
    public void onClick(View v) {
        uoukeId = SPUtils.get(getApplicationContext(), "Id", "").toString();
        if (ButtonUtils.isFastDoubleClick()) {
            return;
        } else {
            switch (v.getId()) {
                case R.id.GoodsValue_BackImg:
                    finish();
                    break;
            }
        }
    }


    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int arg0) {
        if (arg0 == list3.size()) {
            //滑动查看商品信息界面->scrollview
            mVp.setCurrentItem(arg0 - 1);
            mSc.setScrollDown();
            return;
        } else {
            //查找点容器下所有imageview根据索引切换白色点图片
            for (int i = 0; i < list3.size(); i++) {
                ImageView img = (ImageView) mPointLinear.getChildAt(i);
                img.setImageBitmap(nBit);
                if (i == arg0) {
                    img.setImageBitmap(pBit);
                }
            }
        }
    }

}
